package com.gengzp.rpc.core.impl;

import com.gengzp.rpc.constants.RpcCommonConstants;
import com.gengzp.rpc.core.EnvironmentReader;
import com.gengzp.rpc.core.RpcCoreFunc;
import com.gengzp.rpc.model.resp.nacos.NacosOnlineInstanceResp;
import com.gengzp.rpc.utils.RpcHttpRequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
 * @ClassName RpcCoreFunc
 * @Description 远程调用框架核心方法实现类
 * @Author gengzp
 * @Date 2025/6/1 0:11
 */
@Component
public class RpcCoreFuncImpl implements RpcCoreFunc {

    @Autowired
    private EnvironmentReader environmentReader;

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 根据服务名称查询在线的实例url集合
     *
     * @param serviceName 服务名
     * @return 在线实例url集合
     */
    public List<String> searchOnlineServiceUrlByName(String serviceName) {
        // 调用nacos接口, 获取服务实例集合
        NacosOnlineInstanceResp nacosOnlineInstanceResp = RpcHttpRequestUtils.get(
                String.format("%s?serviceName=%s&clusterName=DEFAULT&groupName=%s&pageSize=1000&pageNo=1&namespaceId=%s",
                        String.format("http://%s%s", environmentReader.getCurrentNacosAddress(), RpcCommonConstants.SEARCH_NACOS_ONLINE_SERVICE_INSTANCE_URL),
                        serviceName,
                        environmentReader.getCurrentNacosGroup(),
                        environmentReader.getCurrentNacosNamespace()),
                NacosOnlineInstanceResp.class
        );
        if (nacosOnlineInstanceResp == null || nacosOnlineInstanceResp.getList() == null || nacosOnlineInstanceResp.getList().isEmpty()) {
            return Collections.emptyList();
        }

        return nacosOnlineInstanceResp.getList().stream()
                .map(v -> String.format("%s:%s", v.getIp(), v.getPort())).collect(Collectors.toList());
    }

    @Override
    public String searchCurrentServiceName() {
        return environmentReader.getCurrentNacosNamespace();
    }

    @Override
    public String loadBalanceRemoteServiceUrl(List<String> urls) {
        return urls.get(ThreadLocalRandom.current().nextInt(urls.size()));
    }

    @Override
    public Object getBeanByInterfaceClass(Class<?> interfaceClass) {
        return applicationContext.getBean(interfaceClass);
    }

}
